<%@ page import="org.bson.Document" %>
<%@ page import="com.mongodb.client.*" %>
<%@ page import="org.bson.conversions.Bson" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.LinkedList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%


    request.setCharacterEncoding("utf-8");
    Document student = new Document();


    String sno = request.getParameter("sno");
    student.append("sno", sno);

    String name = request.getParameter("name");
    student.append("name", name);

    String sex = request.getParameter("sex");
    student.append("sex", sex);

    Integer age = Integer.parseInt(request.getParameter("age"));
    student.append("age", age);

    String idCard = request.getParameter("idCard");
    student.append("idCard", idCard);

    String birthDay = request.getParameter("birthDay");
    student.append("birthDay", birthDay);

    String phone = request.getParameter("phone");
    student.append("phone", phone);

    String username = request.getParameter("username");
    student.append("username", username);

    String password = request.getParameter("password");
    student.append("password", password);

    String email = request.getParameter("email");
    student.append("email", email);

    String major = request.getParameter("major");
    student.append("major", major);

    String address = request.getParameter("address");
    student.append("address", address);


    String url = "mongodb://g08:abc%408@mongo.zhledu.cn:27017/g08";
    MongoClient client = MongoClients.create(url);
    MongoIterable<String> names = client.listDatabaseNames();
    MongoDatabase g08 = client.getDatabase("g08");
    MongoCollection<Document> collection = g08.getCollection("student");

    List<Bson> queryList2 = new LinkedList<>();
    Document group2 = new Document();
    group2.append("$group", new Document("_id", 1).append("max", new Document("$max", "$_id")));
    queryList2.add(group2);
    final AggregateIterable<Document> maxSno = collection.aggregate(queryList2);
    int id = 0;
    for (Document d : maxSno) {
        System.out.println(d);
        id = d.getInteger("max") + 1;
        break;
    }
    student.append("_id", id);
    collection.insertOne(student);
    response.getWriter().write("<script language=JavaScript>{window.alert('保存成功!');window.location.href='index.jsp'}</script>");


%>
